package com.esri.core.internal.io.handler;

import com.esri.core.io.EsriSecurityException;
import com.esri.core.io.EsriServiceException;
import com.esri.core.io.HttpRequestHandler;
import com.esri.core.io.HttpRequestListener;
import com.esri.core.io.UserCredentials;
import com.sangfor.ssl.service.utils.IGeneral;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.Serializable;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocketFactory;
import kotlin.jvm.internal.LongCompanionObject;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.cookie.BasicExpiresHandler;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.CharArrayBuffer;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.util.MinimalPrettyPrinter;

/* loaded from: classes.dex */
public abstract class c implements Serializable {
    public static final String a = "UTF-8";
    public static final int b = 3;
    public static final int c = 8192;
    public static final int d = 1200000;
    public static final int e = 1200000;
    protected static final DefaultHttpClient f;
    protected static final ClientConnectionManager g;
    private static final int i = 2000;
    private static final String k = "/";
    private static final String l = "/sharing/rest/";
    private static final String m = "services";
    private static final String n = "mobile";
    private static final String o = "sharing";
    private static final String p = "arcgisoutput";
    private static SSLSocketFactory s = null;
    private static final long serialVersionUID = 1;
    protected static final List<String> h = new ArrayList();
    private static String j = "ArcGIS_AndroidSDK";
    private static String q = com.esri.core.internal.util.f.c;
    private static String r = null;

    static {
        s = null;
        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(basicHttpParams, "UTF-8");
        HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, true);
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 1200000);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 1200000);
        HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192);
        HttpClientParams.setRedirecting(basicHttpParams, false);
        HttpProtocolParams.setUserAgent(basicHttpParams, q);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        e eVar = new e();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", eVar, (int) IGeneral.DEFAULT_SSL_PORT));
        try {
            s = m.a().getSocketFactory();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry);
        g = threadSafeClientConnManager;
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(threadSafeClientConnManager, basicHttpParams);
        f = defaultHttpClient;
        defaultHttpClient.setHttpRequestRetryHandler(new p());
        defaultHttpClient.getAuthSchemes().register("ntlm", new l());
        defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(defaultHttpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
        defaultHttpClient.setRedirectHandler(new DefaultRedirectHandler() { // from class: com.esri.core.internal.io.handler.c.1
            public URI getLocationURI(HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
                return super.getLocationURI(httpResponse, httpContext);
            }
        });
        defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() { // from class: com.esri.core.internal.io.handler.c.2
            public void process(HttpRequest httpRequest, HttpContext httpContext) {
                if (httpRequest.containsHeader(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_ACCEPT_ENCODING)) {
                    return;
                }
                httpRequest.addHeader(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_ACCEPT_ENCODING, com.sangfor.kevinsawicki.http.HttpRequest.ENCODING_GZIP);
            }
        });
        defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() { // from class: com.esri.core.internal.io.handler.c.3
            public void process(HttpRequest httpRequest, HttpContext httpContext) {
                HttpRequestListener httpRequestListener = HttpRequestHandler.getInstance().getHttpRequestListener();
                if (httpRequestListener != null) {
                    httpRequestListener.onRequestInterception(httpRequest, httpContext);
                }
            }
        });
        defaultHttpClient.getCookieSpecs().register("lenient", new CookieSpecFactory() { // from class: com.esri.core.internal.io.handler.c.4
            public CookieSpec newInstance(HttpParams httpParams) {
                return new a();
            }
        });
        HttpClientParams.setCookiePolicy(defaultHttpClient.getParams(), "lenient");
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(new CookiePolicy() { // from class: com.esri.core.internal.io.handler.c.5
            @Override // java.net.CookiePolicy
            public boolean shouldAccept(URI uri, HttpCookie httpCookie) {
                if (httpCookie.getMaxAge() < 1) {
                    httpCookie.setMaxAge(LongCompanionObject.MAX_VALUE);
                    return true;
                }
                return true;
            }
        });
        CookieHandler.setDefault(cookieManager);
        defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { // from class: com.esri.core.internal.io.handler.c.6
            public void process(HttpResponse httpResponse, HttpContext httpContext) {
                Header[] headers;
                if (httpResponse.getStatusLine().getStatusCode() == 302 && (headers = httpResponse.getHeaders(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_LOCATION)) != null) {
                    for (Header header : headers) {
                        if (header.getValue().contains("GPServer") && header.getValue().contains("job")) {
                            HttpHost httpHost = (HttpHost) httpContext.getAttribute("http.target_host");
                            StringBuilder sb = new StringBuilder();
                            sb.append(httpHost.getSchemeName());
                            sb.append("://");
                            sb.append(httpHost.getHostName());
                            sb.append(httpHost.getPort() != -1 ? ":" + httpHost.getPort() : "");
                            sb.append(header.getValue());
                            httpResponse.setReasonPhrase(sb.toString());
                        }
                    }
                }
                Header contentEncoding = httpResponse.getEntity().getContentEncoding();
                if (contentEncoding != null) {
                    for (HeaderElement headerElement : contentEncoding.getElements()) {
                        if (headerElement.getName().equalsIgnoreCase(com.sangfor.kevinsawicki.http.HttpRequest.ENCODING_GZIP)) {
                            httpResponse.setEntity(new b(httpResponse.getEntity()));
                            return;
                        }
                    }
                }
            }
        });
    }

    public static void a(int i2) {
        HttpConnectionParams.setConnectionTimeout(f.getParams(), i2);
    }

    public static void a(String str) {
        q = str;
        HttpProtocolParams.setUserAgent(f.getParams(), a());
    }

    public static void b(String str) {
        r = str;
        HttpProtocolParams.setUserAgent(f.getParams(), a());
    }

    private static String a() {
        if (com.esri.core.internal.util.g.a(r)) {
            return q;
        }
        return r + '/' + q;
    }

    /* loaded from: classes.dex */
    final class a extends BrowserCompatSpec {
        public a() {
            registerAttribHandler("expires", new BasicExpiresHandler(DATE_PATTERNS) { // from class: com.esri.core.internal.io.handler.c.a.1
                public void parse(SetCookie setCookie, String str) throws MalformedCookieException {
                    if (str != null && str.length() > 0) {
                        super.parse(setCookie, str);
                    } else {
                        setCookie.setExpiryDate((Date) null);
                    }
                }
            });
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static HttpURLConnection a(String str, String str2, String str3) throws IOException {
        SSLSocketFactory sSLSocketFactory;
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(str).openConnection();
        httpURLConnection.setConnectTimeout(1200000);
        HttpURLConnection.setFollowRedirects(false);
        httpURLConnection.setRequestProperty("User-Agent", a());
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setChunkedStreamingMode(65536);
        httpURLConnection.setRequestProperty(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_ACCEPT_ENCODING, com.sangfor.kevinsawicki.http.HttpRequest.ENCODING_GZIP);
        if (str2 != null) {
            httpURLConnection.setRequestProperty("Content-Type", str2);
        }
        if (str3 != null) {
            httpURLConnection.setRequestProperty(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_REFERER, str3);
        }
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        if ((httpURLConnection instanceof HttpsURLConnection) && (sSLSocketFactory = s) != null) {
            ((HttpsURLConnection) httpURLConnection).setSSLSocketFactory(sSLSocketFactory);
        }
        return httpURLConnection;
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static String a(HttpURLConnection httpURLConnection) throws IOException {
        InputStreamReader inputStreamReader;
        Throwable th;
        InputStream gZIPInputStream = com.sangfor.kevinsawicki.http.HttpRequest.ENCODING_GZIP.equals(httpURLConnection.getContentEncoding()) ? new GZIPInputStream(httpURLConnection.getInputStream()) : httpURLConnection.getInputStream();
        CharArrayBuffer charArrayBuffer = new CharArrayBuffer(4096);
        try {
            inputStreamReader = new InputStreamReader(gZIPInputStream, "UTF-8");
        } catch (Throwable th2) {
            inputStreamReader = null;
            th = th2;
        }
        try {
            char[] cArr = new char[1024];
            while (true) {
                int read = inputStreamReader.read(cArr);
                if (read != -1) {
                    charArrayBuffer.append(cArr, 0, read);
                } else {
                    inputStreamReader.close();
                    return charArrayBuffer.toString();
                }
            }
        } catch (Throwable th3) {
            th = th3;
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            throw th;
        }
    }

    /* loaded from: classes.dex */
    private static class b extends HttpEntityWrapper {
        public long getContentLength() {
            return -1L;
        }

        public b(HttpEntity httpEntity) {
            super(httpEntity);
        }

        public InputStream getContent() throws IOException, IllegalStateException {
            return new GZIPInputStream(this.wrappedEntity.getContent());
        }
    }

    /* JADX WARN: Removed duplicated region for block: B:12:0x001d A[Catch: EsriServiceException -> 0x0054, HttpResponseException -> 0x0073, SSLException -> 0x0085, TryCatch #2 {HttpResponseException -> 0x0073, EsriServiceException -> 0x0054, SSLException -> 0x0085, blocks: (B:3:0x0006, B:5:0x000c, B:8:0x0011, B:10:0x0019, B:12:0x001d, B:15:0x0025, B:16:0x002a, B:20:0x0039, B:17:0x0030, B:19:0x0034), top: B:40:0x0006 }] */
    /* JADX WARN: Removed duplicated region for block: B:17:0x0030 A[Catch: EsriServiceException -> 0x0054, HttpResponseException -> 0x0073, SSLException -> 0x0085, TryCatch #2 {HttpResponseException -> 0x0073, EsriServiceException -> 0x0054, SSLException -> 0x0085, blocks: (B:3:0x0006, B:5:0x000c, B:8:0x0011, B:10:0x0019, B:12:0x001d, B:15:0x0025, B:16:0x002a, B:20:0x0039, B:17:0x0030, B:19:0x0034), top: B:40:0x0006 }] */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct code enable 'Show inconsistent code' option in preferences
    */
    public static final java.io.InputStream c(java.lang.String r6, java.util.Map<java.lang.String, java.lang.String> r7, com.esri.core.internal.io.handler.n r8) throws java.lang.Exception {
        /*
            java.lang.String r0 = "Invalid or missing user credentials"
            java.lang.String r1 = "Unauthorized"
            r2 = -10001(0xffffffffffffd8ef, float:NaN)
            java.lang.String r3 = a(r6, r8)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            if (r8 == 0) goto L18
            com.esri.core.io.UserCredentials r4 = r8.b     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            if (r4 != 0) goto L11
            goto L18
        L11:
            com.esri.core.io.UserCredentials r4 = r8.b     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            com.esri.core.io.UserCredentials$AuthenticationType r4 = r4.getAuthenticationType()     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            goto L19
        L18:
            r4 = 0
        L19:
            com.esri.core.io.UserCredentials$AuthenticationType r5 = com.esri.core.io.UserCredentials.AuthenticationType.TOKEN     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            if (r4 != r5) goto L30
            java.lang.String r4 = a(r8)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            if (r4 == 0) goto L39
            if (r7 != 0) goto L2a
            java.util.HashMap r7 = new java.util.HashMap     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            r7.<init>()     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
        L2a:
            java.lang.String r5 = "token"
            r7.put(r5, r4)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            goto L39
        L30:
            com.esri.core.io.UserCredentials$AuthenticationType r5 = com.esri.core.io.UserCredentials.AuthenticationType.HTTP     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            if (r4 != r5) goto L39
            com.esri.core.io.UserCredentials r4 = r8.b     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            a(r6, r4)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
        L39:
            java.lang.String r8 = c(r8)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            r4 = 0
            org.apache.http.client.methods.HttpUriRequest r7 = a(r3, r7, r8, r4)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            org.apache.http.impl.client.DefaultHttpClient r8 = com.esri.core.internal.io.handler.c.f     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            org.apache.http.HttpResponse r7 = r8.execute(r7)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            a(r7)     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            org.apache.http.HttpEntity r7 = r7.getEntity()     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            java.io.InputStream r6 = r7.getContent()     // Catch: com.esri.core.io.EsriServiceException -> L54 org.apache.http.client.HttpResponseException -> L73 javax.net.ssl.SSLException -> L85
            return r6
        L54:
            r6 = move-exception
            int r7 = r6.getCode()
            r8 = 401(0x191, float:5.62E-43)
            if (r7 == r8) goto L6d
            java.lang.String r7 = r6.getMessage()
            java.lang.String r7 = r7.trim()
            boolean r7 = r7.contains(r1)
            if (r7 == 0) goto L6c
            goto L6d
        L6c:
            throw r6
        L6d:
            com.esri.core.io.EsriSecurityException r7 = new com.esri.core.io.EsriSecurityException
            r7.<init>(r2, r0, r6)
            throw r7
        L73:
            r6 = move-exception
            java.lang.String r7 = r6.getMessage()
            boolean r7 = r7.contains(r1)
            if (r7 == 0) goto L84
            com.esri.core.io.EsriSecurityException r7 = new com.esri.core.io.EsriSecurityException
            r7.<init>(r2, r0, r6)
            throw r7
        L84:
            throw r6
        L85:
            r7 = move-exception
            com.esri.core.io.EsriSecurityException r8 = new com.esri.core.io.EsriSecurityException
            r0 = -10004(0xffffffffffffd8ec, float:NaN)
            java.lang.StringBuilder r1 = new java.lang.StringBuilder
            r1.<init>()
            java.lang.String r2 = "Untrusted server certificate from "
            r1.append(r2)
            r1.append(r6)
            java.lang.String r6 = r1.toString()
            r8.<init>(r0, r6, r7)
            throw r8
        */
        throw new UnsupportedOperationException("Method not decompiled: com.esri.core.internal.io.handler.c.c(java.lang.String, java.util.Map, com.esri.core.internal.io.handler.n):java.io.InputStream");
    }

    public static HttpResponse a(String str, List<NameValuePair> list, String str2) throws ClientProtocolException, IOException {
        HttpGet b2 = b(str, list, str2);
        b2.getParams().setParameter("http.protocol.handle-redirects", Boolean.TRUE);
        return f.execute(b2);
    }

    public static HttpGet b(String str, List<NameValuePair> list, String str2) {
        String str3;
        String c2 = c(str);
        StringBuilder sb = new StringBuilder();
        sb.append(c2);
        if (list == null || list.isEmpty()) {
            str3 = "";
        } else {
            StringBuilder sb2 = new StringBuilder();
            sb2.append(c2.contains("?") ? "&" : "?");
            sb2.append(URLEncodedUtils.format(list, "UTF-8"));
            str3 = sb2.toString();
        }
        sb.append(str3);
        HttpGet httpGet = new HttpGet(sb.toString());
        if (str2 != null) {
            httpGet.addHeader(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_REFERER, str2);
        }
        return httpGet;
    }

    public static HttpPost c(String str, List<NameValuePair> list, String str2) throws Exception {
        HttpPost httpPost = new HttpPost(c(str));
        if (list != null && !list.isEmpty()) {
            httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
        }
        if (str2 != null) {
            httpPost.addHeader(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_REFERER, str2);
        }
        return httpPost;
    }

    public static HttpPost a(String str, String str2) throws IOException {
        HttpPost httpPost = new HttpPost(c(str));
        if (com.esri.core.internal.util.g.b(str2)) {
            httpPost.setEntity(new StringEntity(str2, "UTF-8"));
        }
        return httpPost;
    }

    public static HttpUriRequest a(String str, Map<String, String> map, String str2, boolean z) throws Exception {
        ArrayList arrayList = new ArrayList();
        a(map, arrayList);
        if (!z) {
            HttpGet b2 = b(str, arrayList, str2);
            if (b2.getURI().toASCIIString().length() < 2000) {
                return b2;
            }
        }
        return c(str, arrayList, str2);
    }

    public static final void a(Map<String, String> map, List<NameValuePair> list) throws Exception {
        if (map == null || map.isEmpty()) {
            return;
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!e(key) && value != null) {
                list.add(new BasicNameValuePair(key, value));
            }
        }
    }

    private static final boolean e(String str) {
        return str == null || str.length() < 1;
    }

    public static void a(KeyStore keyStore) throws EsriSecurityException {
        a((KeyStore) null, (String) null, keyStore);
    }

    public static void a(KeyStore keyStore, String str, KeyStore keyStore2) throws EsriSecurityException {
        try {
            f.getConnectionManager().getSchemeRegistry().register(new Scheme("https", new e(keyStore, str, keyStore2), (int) IGeneral.DEFAULT_SSL_PORT));
            s = m.a(keyStore, str, keyStore2).getSocketFactory();
        } catch (Exception e2) {
            throw new EsriSecurityException(e2);
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final String a(String str, JsonParser jsonParser, String str2, EsriSecurityException[] esriSecurityExceptionArr, int i2, n nVar) throws Exception {
        if (str.length() <= 14 || str.substring(0, 15).indexOf("\"error\"") <= -1) {
            return null;
        }
        EsriServiceException fromJson = EsriServiceException.fromJson(jsonParser);
        if (fromJson.getMessage().trim().contains("Invalid token") || fromJson.getCode() == 498) {
            if (b(nVar) != null && i2 < 3) {
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }
                a(nVar, i2 + 1);
                return str2;
            }
            esriSecurityExceptionArr[0] = new EsriSecurityException(EsriSecurityException.TOKEN_INVALID, "Invalid token used to access a secure service - " + str2);
            return null;
        } else if (fromJson.getMessage().trim().contains("Unauthorized access") || fromJson.getCode() == 401 || fromJson.getCode() == 499 || fromJson.getCode() == 403) {
            if (fromJson.getCode() == 403 && fromJson.getMessage().trim().toLowerCase().contains("ssl") && !str2.startsWith("https")) {
                return str2.replace("http", "https");
            }
            if (d(nVar) != null && i2 < 3) {
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedIOException();
                }
                a(nVar, i2 + 1);
                return str2;
            }
            esriSecurityExceptionArr[0] = new EsriSecurityException(-10001, "Unauthorized access to a secure service - " + str2);
            return null;
        } else {
            throw fromJson;
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final void a(HttpResponse httpResponse) {
        Header firstHeader;
        StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() >= 400 || httpResponse.getEntity() == null) {
            throw new EsriServiceException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }
        if (statusLine.getStatusCode() == 302 || statusLine.getStatusCode() == 301) {
            String reasonPhrase = statusLine.getReasonPhrase();
            if (!reasonPhrase.contains("?") && (firstHeader = httpResponse.getFirstHeader(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_LOCATION)) != null) {
                reasonPhrase = firstHeader.getValue();
            }
            throw new EsriServiceException(statusLine.getStatusCode(), reasonPhrase);
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final void b(HttpURLConnection httpURLConnection) {
        String headerField;
        try {
            if (httpURLConnection.getResponseCode() >= 400) {
                throw new EsriServiceException(httpURLConnection.getResponseCode(), httpURLConnection.getResponseMessage());
            }
            if (httpURLConnection.getResponseCode() != 302 && httpURLConnection.getResponseCode() != 301) {
                return;
            }
            String responseMessage = httpURLConnection.getResponseMessage();
            if (!responseMessage.contains("?") && (headerField = httpURLConnection.getHeaderField(com.sangfor.kevinsawicki.http.HttpRequest.HEADER_LOCATION)) != null) {
                responseMessage = headerField;
            }
            throw new EsriServiceException(httpURLConnection.getResponseCode(), responseMessage);
        } catch (IOException e2) {
            throw new RuntimeException(e2);
        }
    }

    public static void a(String str, int i2) {
        a(str, i2, "http");
    }

    public static void a(String str, int i2, String str2) {
        final HttpHost httpHost = new HttpHost(str, i2, str2);
        f.setRoutePlanner(new HttpRoutePlanner() { // from class: com.esri.core.internal.io.handler.c.7
            public HttpRoute determineRoute(HttpHost httpHost2, HttpRequest httpRequest, HttpContext httpContext) {
                InetAddress localAddress = ConnRouteParams.getLocalAddress(httpRequest.getParams());
                boolean equalsIgnoreCase = "https".equalsIgnoreCase(httpHost2.getSchemeName());
                if (httpHost2.getHostName().equals("127.0.0.1") || httpHost2.getHostName().equalsIgnoreCase("localhost")) {
                    return new HttpRoute(httpHost2, localAddress, equalsIgnoreCase);
                }
                return new HttpRoute(httpHost2, localAddress, httpHost, equalsIgnoreCase);
            }
        });
    }

    public static String a(n nVar, int i2) throws EsriSecurityException {
        if (nVar.b instanceof k) {
            return b(nVar, i2);
        }
        return c(nVar, i2);
    }

    private static String b(n nVar, int i2) {
        k kVar = (k) nVar.b;
        try {
            kVar.f();
            return kVar.getToken();
        } catch (Exception e2) {
            e2.printStackTrace();
            return "";
        }
    }

    private static String c(n nVar, int i2) throws EsriSecurityException {
        URL url;
        String str;
        String str2;
        String str3;
        String str4;
        String str5;
        boolean z;
        boolean z2;
        UserCredentials userCredentials = nVar.b;
        String str6 = nVar.a;
        try {
            URL url2 = nVar.a() != null ? new URL(nVar.a()) : null;
            if (url2 == null) {
                try {
                    if (str6.contains("rest/")) {
                        str = str6.substring(0, str6.lastIndexOf("rest/") + 5) + "info";
                    } else if (str6.contains("rest")) {
                        str = str6.substring(0, str6.lastIndexOf("rest") + 4) + "/info";
                    } else {
                        str = str6;
                    }
                    ArrayList arrayList = new ArrayList();
                    HashMap hashMap = new HashMap();
                    hashMap.put("f", "json");
                    a(hashMap, arrayList);
                    try {
                        str2 = (String) f.execute(b(str, arrayList, c(nVar)), new BasicResponseHandler());
                    } catch (Exception unused) {
                        System.err.println("Server does not support the info operation " + str);
                        str2 = null;
                    }
                    if (str2 == null || (str2.length() > 14 && str2.substring(0, 15).indexOf("\"error\"") > -1)) {
                        str3 = str6.substring(0, str6.lastIndexOf(f(str6))) + "/tokens";
                    } else {
                        try {
                            JsonParser c2 = com.esri.core.internal.util.d.c(str2);
                            c2.nextToken();
                            if (c2.getCurrentToken() == JsonToken.START_OBJECT) {
                                str4 = null;
                                str3 = null;
                                while (c2.nextToken() != JsonToken.END_OBJECT) {
                                    String currentName = c2.getCurrentName();
                                    c2.nextToken();
                                    if (currentName.equals("owningSystemUrl")) {
                                        str4 = c2.getText();
                                    } else if (currentName.equals("authInfo")) {
                                        if (c2.getCurrentToken() == JsonToken.START_OBJECT) {
                                            while (c2.nextToken() != JsonToken.END_OBJECT) {
                                                String currentName2 = c2.getCurrentName();
                                                c2.nextToken();
                                                if (currentName2.equals("tokenServicesUrl")) {
                                                    str3 = c2.getText();
                                                } else {
                                                    c2.skipChildren();
                                                }
                                            }
                                        }
                                    } else {
                                        c2.skipChildren();
                                    }
                                }
                            } else {
                                str4 = null;
                                str3 = null;
                            }
                            c2.close();
                            if (str4 != null && str4.length() > 0) {
                                str3 = str4.replace("http:", "https:") + "/sharing/generateToken";
                            }
                        } catch (JsonParseException unused2) {
                            str3 = str6.substring(0, str6.lastIndexOf(f(str6))) + "/tokens";
                        }
                    }
                    URL url3 = new URL(str3);
                    try {
                        nVar.c(url3.toExternalForm());
                        url2 = url3;
                    } catch (Exception e2) {
                        e = e2;
                        url = url3;
                        if (e instanceof EsriSecurityException) {
                            throw ((EsriSecurityException) e);
                        }
                        if (e instanceof SSLException) {
                            throw new EsriSecurityException(EsriSecurityException.UNTRUSTED_SERVER_CERTIFICATE, "Untrusted server certificate from " + url, e);
                        } else if (e instanceof HttpHostConnectException) {
                            throw new EsriSecurityException(EsriSecurityException.TOKEN_SERVICE_NOT_FOUND, "Could not find a token service running on " + url);
                        } else {
                            throw new EsriSecurityException(-10001, "Error while generating a token", e);
                        }
                    }
                } catch (Exception e3) {
                    e = e3;
                    url = url2;
                }
            } else {
                str3 = null;
            }
            boolean z3 = userCredentials != null && (userCredentials instanceof com.esri.core.internal.io.handler.b);
            com.esri.core.internal.io.handler.b bVar = z3 ? userCredentials : null;
            ArrayList arrayList2 = new ArrayList();
            HashMap hashMap2 = new HashMap();
            if (!z3 || (z3 && bVar != null && bVar.a.getUrl().endsWith("arcgis.com"))) {
                hashMap2.put("username", userCredentials.getUserName());
                hashMap2.put("password", userCredentials.getPassword());
            }
            hashMap2.put("clientid", "ref." + j);
            hashMap2.put("_servicesUrl", "1");
            hashMap2.put("request", "gettoken");
            boolean endsWith = url2.toExternalForm().endsWith("generateToken");
            if (endsWith) {
                if (z3) {
                    hashMap2.put("token", a(userCredentials));
                    hashMap2.put("serverUrl", bVar.b());
                }
                hashMap2.put("referer", j);
                hashMap2.put("f", "json");
            }
            a(hashMap2, arrayList2);
            try {
                str5 = (String) f.execute(c(url2.toExternalForm(), arrayList2, c(nVar)), new BasicResponseHandler());
            } catch (HttpResponseException e4) {
                if (str3 != null) {
                    if (e4.getStatusCode() == 401) {
                        a(str3, userCredentials);
                        try {
                            str5 = (String) f.execute(c(str3, arrayList2, c(nVar)), new BasicResponseHandler());
                        } catch (HttpResponseException e5) {
                            throw new EsriSecurityException(-10001, "Error while generating a token from " + str3, e5);
                        }
                    }
                } else if (e4.getStatusCode() == 404) {
                    throw new EsriSecurityException(EsriSecurityException.TOKEN_SERVICE_NOT_FOUND, "Could not find a token service running on " + url2);
                } else if (e4.getStatusCode() == 401) {
                    throw new EsriSecurityException(-10001, "Error while generating a token from " + url2, e4);
                }
                str5 = null;
            }
            String trim = str5 == null ? null : str5.trim();
            long j2 = 0;
            if (endsWith) {
                JsonParser c3 = com.esri.core.internal.util.d.c(trim);
                if (com.esri.core.internal.util.d.c(c3)) {
                    String str7 = trim;
                    trim = null;
                    boolean z4 = true;
                    while (c3.nextToken() != JsonToken.END_OBJECT) {
                        String currentName3 = c3.getCurrentName();
                        c3.nextToken();
                        if (currentName3.equals("token")) {
                            trim = c3.getText();
                        } else if (currentName3.equals("ssl")) {
                            nVar.a(c3.getBooleanValue());
                        } else if (currentName3.equals("expires")) {
                            j2 = c3.getLongValue();
                        } else if (!currentName3.equals("error")) {
                            c3.skipChildren();
                        } else if (z3 && i2 < 3) {
                            String c4 = bVar.c();
                            if (c4 != null) {
                                j2 = bVar.getTokenExpiry();
                                str7 = c4;
                            } else {
                                z4 = false;
                            }
                            c3.nextToken();
                        } else {
                            String str8 = null;
                            String str9 = null;
                            while (c3.nextToken() != JsonToken.END_OBJECT) {
                                String currentName4 = c3.getCurrentName();
                                c3.nextToken();
                                if (currentName4.equals("message")) {
                                    str9 = c3.getText();
                                } else if (currentName4.equals("details")) {
                                    str8 = "";
                                    while (c3.nextToken() != JsonToken.END_ARRAY) {
                                        str8 = str8 + c3.getText() + ", ";
                                    }
                                    if (str8.endsWith(", ")) {
                                        str8 = str8.substring(0, str8.lastIndexOf(", "));
                                    }
                                }
                            }
                            throw new EsriSecurityException(-10001, "Message: " + str9 + " Details: " + str8);
                        }
                    }
                    if (trim == null || "".equals(trim)) {
                        trim = str7;
                    }
                    z = z4;
                    if (trim != null || trim.contains(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR)) {
                        if (!z3 && i2 < 3) {
                            String c5 = bVar.c();
                            if (c5 != null) {
                                trim = c5;
                                z2 = z;
                                j2 = bVar.getTokenExpiry();
                            } else {
                                z2 = false;
                            }
                            z = z2;
                        } else {
                            throw new EsriSecurityException(-10001, trim);
                        }
                    }
                    if (z) {
                        userCredentials.setUserToken(trim, j2, j);
                    }
                    return trim;
                }
            }
            z = true;
            if (trim != null) {
            }
            if (!z3) {
            }
            throw new EsriSecurityException(-10001, trim);
        } catch (Exception e6) {
            e = e6;
            url = null;
        }
    }

    private static final String f(String str) {
        Matcher matcher = Pattern.compile(".*(/.*?rest/)").matcher(str);
        String str2 = "";
        while (matcher.find()) {
            str2 = matcher.group(1);
        }
        return str2;
    }

    private static final String a(UserCredentials userCredentials) {
        UserCredentials a2 = ((com.esri.core.internal.io.handler.b) userCredentials).a();
        return a2 == null ? userCredentials.getToken() : a2.getToken();
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final String a(n nVar) throws EsriSecurityException {
        if (nVar == null || nVar.b == null) {
            return null;
        }
        String token = nVar.b.getToken();
        if (token != null) {
            return token;
        }
        if (nVar.b.getAuthenticationType() == UserCredentials.AuthenticationType.TOKEN && (token = a(nVar, 1)) == null) {
            throw new EsriSecurityException((int) EsriSecurityException.TOKEN_SERVICE_NOT_FOUND);
        }
        return token;
    }

    static final String b(n nVar) {
        if (nVar != null) {
            return nVar.a();
        }
        return null;
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final String c(n nVar) {
        if (nVar == null || nVar.b == null) {
            return null;
        }
        return nVar.b.getReferer();
    }

    static final String d(n nVar) {
        if (nVar != null) {
            return nVar.a;
        }
        return null;
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final boolean e(n nVar) {
        return (nVar == null || nVar.b == null || nVar.b.getAuthenticationType() != UserCredentials.AuthenticationType.TOKEN) ? false : true;
    }

    public static final void a(String str, UserCredentials userCredentials) throws EsriSecurityException {
        try {
            URL url = new URL(str);
            String b2 = b(url);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort() != -1 ? url.getPort() : -1, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
            AuthScope authScope2 = new AuthScope(url.getHost(), url.getPort() != -1 ? url.getPort() : -1, AuthScope.ANY_REALM, "ntlm");
            if (userCredentials != null) {
                DefaultHttpClient defaultHttpClient = f;
                defaultHttpClient.getCredentialsProvider().setCredentials(authScope, new UsernamePasswordCredentials(userCredentials.getUserName(), userCredentials.getPassword()));
                defaultHttpClient.getCredentialsProvider().setCredentials(authScope2, new NTCredentials(userCredentials.getUserName(), userCredentials.getPassword(), url.getHost(), userCredentials.getDomain()));
                List<String> list = h;
                if (list.contains(b2)) {
                    return;
                }
                list.add(b2);
                return;
            }
            DefaultHttpClient defaultHttpClient2 = f;
            if (defaultHttpClient2.getCredentialsProvider().getCredentials(authScope) != null) {
                defaultHttpClient2.getCredentialsProvider().setCredentials(authScope, (Credentials) null);
            }
            if (defaultHttpClient2.getCredentialsProvider().getCredentials(authScope2) != null) {
                defaultHttpClient2.getCredentialsProvider().setCredentials(authScope2, (Credentials) null);
            }
            List<String> list2 = h;
            if (list2.contains(b2)) {
                list2.remove(b2);
            }
        } catch (MalformedURLException unused) {
            throw new EsriSecurityException(-10001);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static String b(URL url) {
        if (url == null || url.toExternalForm().length() == 0) {
            return null;
        }
        String path = url.getPath();
        String[] split = path.toLowerCase().split(k);
        StringBuilder sb = new StringBuilder(url.getHost());
        if (split.length < 3) {
            if (!path.startsWith(k) && !path.isEmpty()) {
                sb.append(k);
            }
            sb.append(path);
        } else if ((path.contains(m) || path.contains(p)) && !path.contains(l)) {
            if (!split[1].startsWith(k) && !split[1].isEmpty()) {
                sb.append(k);
            }
            sb.append(split[1]);
        } else if ((!path.contains(o) && split[2].equals(n)) || (path.contains(l) && !split[1].equals(o))) {
            if (!split[1].startsWith(k) && !split[1].isEmpty()) {
                sb.append(k);
            }
            sb.append(split[1]);
        }
        return sb.toString();
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    public static final String a(String str, n nVar) {
        return nVar == null ? str : nVar.b(str);
    }

    public static String c(String str) {
        if (str == null || str.contains("%")) {
            return str;
        }
        try {
            URL url = new URL(str);
            return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()).toURL().toString();
        } catch (Exception unused) {
            return str;
        }
    }

    public static UserCredentials.AuthenticationType d(final String str) {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("Must pass in a non-null, non empty string for service URL");
        }
        final UserCredentials userCredentials = new UserCredentials();
        userCredentials.setAuthenticationType(UserCredentials.AuthenticationType.UNKNOWN);
        FutureTask futureTask = new FutureTask(new Callable<Void>() { // from class: com.esri.core.internal.io.handler.c.8
            /* JADX WARN: Removed duplicated region for block: B:42:0x00e2 A[Catch: Exception -> 0x00f3, TRY_ENTER, TRY_LEAVE, TryCatch #5 {Exception -> 0x00f3, blocks: (B:42:0x00e2, B:50:0x00ef), top: B:70:0x0001 }] */
            /* JADX WARN: Removed duplicated region for block: B:65:0x00fc A[EXC_TOP_SPLITTER, SYNTHETIC] */
            @Override // java.util.concurrent.Callable
            /* renamed from: a */
            /*
                Code decompiled incorrectly, please refer to instructions dump.
                To view partially-correct code enable 'Show inconsistent code' option in preferences
            */
            public java.lang.Void call() {
                /*
                    Method dump skipped, instructions count: 263
                    To view this dump change 'Code comments level' option to 'DEBUG'
                */
                throw new UnsupportedOperationException("Method not decompiled: com.esri.core.internal.io.handler.c.AnonymousClass8.call():java.lang.Void");
            }
        });
        new Thread(futureTask).start();
        try {
            futureTask.get(120L, TimeUnit.SECONDS);
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return userCredentials.getAuthenticationType();
    }

    public static void a(Map<String, String> map, final n nVar) throws EsriSecurityException {
        UserCredentials.AuthenticationType authenticationType = (nVar == null || nVar.b == null) ? null : nVar.b.getAuthenticationType();
        if (authenticationType == UserCredentials.AuthenticationType.TOKEN) {
            String a2 = a(nVar);
            if (a2 != null) {
                map.put("token", a2);
            }
        } else if (authenticationType == UserCredentials.AuthenticationType.HTTP) {
            if (nVar == null) {
                Authenticator.setDefault(null);
            } else {
                Authenticator.setDefault(new Authenticator() { // from class: com.esri.core.internal.io.handler.c.9
                    @Override // java.net.Authenticator
                    protected PasswordAuthentication getPasswordAuthentication() {
                        System.setProperty("http.auth.ntlm.domain", n.this.b.getDomain());
                        return new PasswordAuthentication(n.this.b.getUserName(), n.this.b.getPassword().toCharArray());
                    }
                });
            }
        }
    }
}
